import Vue from 'vue';
import { listData4ExceptionGoods, loadListCellular, listLimit, loadCompeteStoreNames } from './api';
import { export_json_to_excel, formatJson } from '@/utils/vendor/Export2Excel';
import { message } from '@/utils/util';
import { parseToObject } from '@/utils';
import { ChannelTree } from '@/components';
import { GoodsDetailModal } from '@/views/manual-price/components/index';

Vue.component(ChannelTree.name);
Vue.component(GoodsDetailModal.name);

export default {
  components: { ChannelTree, GoodsDetailModal },
  name: 'audit-price-exception-edit-modal',
  props: {
    visible: {
      type: Boolean,
      default: true,
    },
    topChannelList: {
      type: Array,
      default: () => [],
    },
    taskValueString: {
      type: String,
      default: null,
    },
  },

  data() {
    return {
      task: {},
      labelWidth: '100px',
      cellularList: [],
      cellularMap: new Map(),
      formQuery: {},
      onSubmitIng: false,
      channels: [],
      cellulars: [],
      querying: false,
      data: [],
      loading: false,
      total: 0,
      pageSize: 10,
      currentPage: 1,
      exporting: false,
      goodsDetailVisible: false,
      goodsDetail: {},
      competeStoreNames: [],
    };
  },
  watch: {
    taskValueString(newValue) {
      if (!newValue) {
        return;
      }
      this.task = {
        ...this.task,
        ...parseToObject(newValue),
      };
      this.formQuery = { ...this.formQuery, taskId: this.task.id, topChannelCode: this.task.topChannelCode };
      if (this.task.id) {
        this.onQuery();
        this.topChannelChange(this.task.topChannelCode);
      }
    },
  },
  methods: {
    //详情页面列表数据获取 zhouwenkai
    async listData(form, page, isImport) {
      if (!form.taskId) {
        message('错误', 'taskId不存在', 'error');
        return;
      }
      if (!form.topChannelCode) {
        message('错误', '请选择顶级渠道', 'error');
        return;
      }
      try {
        if (!isImport) {
          this.loading = true;
          this.querying = true;
        }
        const result = await listData4ExceptionGoods(form, page);
        const { rows: data = [], total = 0 } = result || {};
        //封装商品请求参数
        const channelGoodsMap = new Map();
        data.forEach(item => {
          const channelCode = item.channelCode;
          const goodsCodes = channelGoodsMap.get(channelCode);
          if (!goodsCodes) {
            const codes = [];
            codes.push(item.goodsCode);
            channelGoodsMap.set(channelCode, codes);
          } else {
            goodsCodes.push(item.goodsCode);
            channelGoodsMap.set(channelCode, goodsCodes);
          }
        });
        const postLimitArray = [];
        channelGoodsMap.forEach(function(value, key) {
          postLimitArray.push(listLimit(key, value));
        });
        //获取商品是否限购
        let postLimitList = [];
        try {
          postLimitList = await Promise.all(postLimitArray);
        } catch (e) {
          message('错误', '获取限购规则失败', 'error');
        }
        const goodsLimitMap = new Map();
        if (postLimitList && postLimitList.length > 0) {
          postLimitList.map(item => {
            item.map(limitItem => {
              const key = limitItem.channelCode + limitItem.goodsCode;
              goodsLimitMap.set(key, limitItem);
            });
          });
        }
        const resultData = data.map(item => {
          const goodsLimit = goodsLimitMap.get(item.channelCode + item.goodsCode);
          let limit = goodsLimit && (goodsLimit.limitNum > 0 || goodsLimit.activityPriceLimit > 0) ? '是' : '否';
          let profitRate = this.getProfitRate(item.costPrice, item.channelPrice) + '%';
          return {
            ...item,
            profitRate: profitRate,
            cellularName: this.cellularMap.get(item.cellularCode)?.cellularName,
            limit: limit,
          };
        });
        if (!isImport) {
          this.data = resultData;
          this.total = total;
        }
        if (isImport) {
          return resultData;
        }
      } catch (e) {
        message('错误', '获取数据失败', 'error');
      }
      if (!isImport) {
        this.loading = false;
        this.querying = false;
      }
    }, //end  listData
    //获取全部蜂窝
    async listCellular() {
      try {
        this.cellularList = (await loadListCellular()) || [];
        if (this.cellularList.length > 0) {
          this.cellularList.forEach(item => {
            this.cellularMap.set(item.cellularCode, item);
          });
        }
      } catch (e) {
        message('错误', '获取蜂窝失败', 'error');
      }
    },
    async listCompeteStoreNames(cellularCode) {
      try {
        this.competeStoreNames = await loadCompeteStoreNames(cellularCode);
      } catch (e) {
        message('错误', '获取竞对门店失败', 'error');
      }
    },
    resetTable() {
      this.$emit('resetTable');
    },
    onClose() {
      this.task = {};
      this.formQuery = {};
      (this.channels = []), (this.cellulars = []), (this.querying = false), (this.data = []);
      this.loading = false;
      this.total = 0;
      this.pageSize = 10;
      this.currentPage = 1;
      this.exporting = false;
      this.$emit('close');
    },
    //渠道选中
    affirmChannel(channels) {
      this.channels = channels;
      this.formQuery.channelCodes = this.channels.map(item => item.id);
    },
    //顶级渠道变更
    topChannelChange(code) {
      this.cellulars = [];
      if (code) {
        this.cellularList.forEach(item => {
          if (item.topChannelCode === code) {
            this.cellulars.push(item);
          }
        });
      }
      this.formQuery = { ...this.formQuery, cellularCode: null };
    },
    async onQuery() {
      const page = { pageSize: this.pageSize, pageNum: this.currentPage };
      await this.listData(this.formQuery, page, false);
    },
    reset() {
      alert(this.formQuery.taskId);
      this.formQuery = { taskId: this.formQuery.taskId };
      alert(this.formQuery.taskId);
    },
    onPageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.onQuery();
    },
    onPageNumChange(pageNum) {
      this.currentPage = pageNum;
      this.onQuery();
    },
    toStatusText(statusType) {
      if (statusType == 'INIT') {
        return '待处理';
      } else if (statusType == 'SUCCESS') {
        return '已处理';
      } else if (statusType == 'FAILURE') {
        return '处理失败';
      } else if (statusType == 'PROCESSED') {
        return '处理中';
      }
      return '无效状态';
    },

    async exportGoodsPrice() {
      try {
        this.exporting = true;
        const form = { ...this.formQuery, taskId: this.task.id, topChannelCode: this.task.topChannelCode };
        const list = await this.listData(form, { pageSize: this.total !== 0 ? this.total : 10000, pageNum: 1, countSql: false }, true);
        if (list && list.length > 0) {
          const listNew = list.map(itemx => ({ ...itemx, status: this.toStatusText(itemx.status) }));
          const tHeader = [
            'id',
            'etid',
            '商品名称',
            '成本价',
            '零售价',
            '毛利率',
            '起送价',
            '商品原价',
            '商品特价',
            '销售排名',
            '竞对原价最低价',
            '竞对特价最低价',
            '调原价',
            '调特价',
            '竞对最高销量',
            '蜂窝总销量',
            '限购规则',
            '状态',
            '原因',
            '月售',
            '限购频率',
            '限购数量',
            '特价限购',
            '商品编码',
            '渠道编码',
            '所属蜂窝',
          ];
          const filterVal = [
            'id',
            'exceptionTaskId',
            'goodsName',
            'costPrice',
            'retailPrice',
            'profitRate',
            'minPrice',
            'channelPrice',
            'activityPrice',
            'salesRank',
            'competeChannelPrice',
            'competeActivityPrice',
            'newChannelPrice',
            'newActivityPrice',
            'competeMaxSales',
            'cellularSales',
            'limit',
            'status',
            'reason',
            'monthSales',
            'limitFrequency',
            'limitNum',
            'activityPriceLimit',
            'goodsCode',
            'channelCode',
            'cellularCode',
          ];
          const data = formatJson(filterVal, listNew);
          export_json_to_excel(tHeader, data, '商品价格信息-' + this.task.id);
        } else {
          message('提示', '没有可导出的数据', 'warning');
        }
        this.exporting = false;
      } catch (e) {
        this.exporting = false;
        message('提示', '导出列表异常', 'error');
      }
    },
    onOpenImportModal() {
      this.$emit('onOpenImportModal', this.task.id);
    },
    //计算毛利率
    getProfitRate(costPrice, channelPrice) {
      if (!costPrice || !channelPrice) {
        return 0;
      }
      return parseFloat((((channelPrice - costPrice) / channelPrice) * 100).toFixed(2));
    },
    async onOpenGoodsDetailModal(row) {
      await this.listCompeteStoreNames(row.cellularCode);
      this.goodsDetail = row;
      this.goodsDetailVisible = true;
    },
    onCloseGoodsDetailModal() {
      this.goodsDetailVisible = false;
      this.goodsDetail = {};
      this.competeStoreNames = [];
    },
  },
  mounted() {
    this.listCellular();
  },
};
